import { Space, Table, Button, Modal, Switch } from 'antd'
import { DeleteOutlined, ExclamationCircleOutlined, EditOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import React, { useEffect, useState } from 'react'
import axios from '../../../utils/request'
import AddUserForm from '../../user-manage/AddUserForm'
import UpdUserForm from '../../user-manage/UpdUserForm'
import PubSub from 'pubsub-js'

const { confirm } = Modal

interface IUser {
  id: number
  username: string
  password: string | number
  roleState: boolean
  default: boolean
  region: string
  roleId: number
  role: IRole[]
}

interface IRole {
  id: number
  roleName: string
  roleType: number
  rights: string[]
}
interface IRegion {
  id: number
  title: string
  value: string
}

const App: React.FC = () => {
  const [userList, setuserList] = useState<IUser[]>([])
  const [regionList, setregionList] = useState<IRegion[]>([])
  function getUserList() {
    axios.get('/users/?_expand=role')
    .then(({ data }) => {
      const {roleId, region} = JSON.parse((localStorage.getItem('token') as string))
      if(roleId === 2){
        data = data.filter((item: IUser) => item.region === region)
        data = data.filter((item: IUser) => item.roleId === 3)
      }
      if(roleId === 3){
        data = []
      }
      setuserList(data)
    })
  }
  useEffect(() => {
    getUserList()
    axios.get('/regions')
    .then(({ data }) => setregionList(data))

    let pubId = PubSub.subscribe('updUserList', () => getUserList())
    return () => {PubSub.unsubscribe(pubId)}
  }, [])
  const showDeleteConfirm = (item: IUser) => {
    confirm({
      title: 'Are you sure delete this task?',
      icon: <ExclamationCircleOutlined />,
      content: 'Some descriptions',
      okText: 'Yes',
      okType: 'danger',
      cancelText: 'No',
      onOk() {
        return axios.delete(`/users/${item.id}`)
        .then(() => getUserList())
      },
      onCancel() {
        console.log('Cancel')
      },
    })
  }
  const columns: ColumnsType<IUser> = [
    {
      title: '区域',
      dataIndex: 'region',
      filters: [
        ...regionList.map(item => ({
          text: item.title,
          value: item.value
        })),
        {
          text: '全球',
          value: '全球'
        }
      ],
      onFilter: (value, item) => {
        if(value === '全球'){
          return item.region === ''
        }
        return item.region === value
      },
      render: (region: string) => region ? region : '全球'
    },
    {
      title: '角色名称',
      dataIndex: 'role',
      render: (role: IRole) => role.roleName
    },
    {
      title: '用户名',
      dataIndex: 'username'
    },
    {
      title: '用户状态',
      dataIndex: 'roleState',
      render: (roleState: boolean, item: IUser) => <Switch checked={roleState} disabled={item.default} onChange={() => {
        axios.patch(`/users/${item.id}`, {roleState: !roleState})
        .then(() => getUserList())
      }}/>
    },
    {
      title: 'Action',
      render: (item: IUser) => (
        <Space size="middle">
          <Button type="primary" danger ghost shape="circle" icon={<DeleteOutlined />} onClick={() => showDeleteConfirm(item)} disabled={item.default}/>
          <UpdUserForm disabled={item.default} currentUser={item}></UpdUserForm>
        </Space>
      ),
    },
  ]
  return (
    <div>
      <AddUserForm></AddUserForm>
      <Table columns={columns} dataSource={userList} rowKey={(item) => item.id} pagination={{pageSize: 5}}/>
    </div>
  )
}

export default App
